package com.wanlian.dao.impl;

import com.wanlian.common.ConstantCode;
import com.wanlian.common.PageCondition;
import com.wanlian.common.RankType;
import com.wanlian.dao.ScoreHistoryDao;
import com.wanlian.dao.UserScoreDao;
import com.wanlian.entity.Device;
import com.wanlian.entity.ScoreHistory;
import com.wanlian.entity.UserScore;
import com.wanlian.model.ResultModel;
import com.wanlian.util.DateUtil;
import com.wanlian.util.Utils;
import com.wanlian.vo.Page;
import com.wanlian.vo.ScoreVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class ScoreHistoryDaoImpl extends GenericDaoImpl<ScoreHistory> implements ScoreHistoryDao {

    @Autowired
    public UserScoreDao userScoreDao;

    public ScoreHistoryDaoImpl() {
        super(ScoreHistory.class);
    }


    @Override
    public ResultModel queryScoreHistory(Page page, Map<String, Object> conditions) {
        ResultModel resultModel = new ResultModel();
        List<ScoreHistory> lists = new ArrayList<ScoreHistory>();
        String hql = String.format("from %s ", entityClassName());
        lists = this.queryForListByPage(hql, null, page);

        String coungHql = String.format("select count(*) from %s ", entityClassName());
        Long count = this.queryCount(coungHql, null);
        resultModel.setBresult(true);
        resultModel.setObject(lists);
        resultModel.setCount(count);
        return resultModel;

    }

    @Override
    public ResultModel queryScoreHistoryByDeviceId(Page page, int deviceId) {
        ResultModel resultModel = new ResultModel();
        List<ScoreHistory> lists = new ArrayList<ScoreHistory>();
        String hql = String.format("from %s where deviceId=?", entityClassName());
        lists = this.queryForListByPage(hql, new Object[]{deviceId}, page);

        String coungHql = String.format("select count(*) from %s where deviceId=?", entityClassName());
        Long count = this.queryCount(coungHql, new Object[]{deviceId});
        resultModel.setBresult(true);
        resultModel.setObject(lists);
        resultModel.setCount(count);
        return resultModel;
    }

    /**
     * 获取某个设备昨日的积分记录
     *
     * @param page
     * @param deviceId
     * @return
     */
    @Override
    public ResultModel queryHistoryYestoryDayByDeviceId(Page page, int deviceId) {
        List<ScoreHistory> lists = new ArrayList<ScoreHistory>();
        Date dateNow = DateUtil.currentDate();
        Date dateEnd = DateUtil.addDay(DateUtil.currentDate(), 1);
        try {
            String startDate = DateUtil.formatDateNoHour(dateNow);
            String endDate = DateUtil.formatDateNoHour(dateEnd);
            String hql = String.format("from %s where deviceId=? and ( addTime between ? and ?)", entityClassName());
            lists = this.queryForListByPage(hql, new Object[]{deviceId, startDate, endDate}, page);
            String coungHql = String.format("select count(*) from %s where deviceId=? and ( addTime between ? and ?)", entityClassName());
            Long count = this.queryCount(coungHql, new Object[]{deviceId, startDate, endDate});
            ResultModel resultModel = new ResultModel(true, lists, count);
            return resultModel;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new ResultModel(false);
    }

    /**
     * 获取用户昨日的积分记录
     *
     * @param userId
     * @return
     */
    @Override
    public List<ScoreHistory> queryHistoryByYesAndUserId(int userId) {
        try {
            Date dateStart = DateUtil.addDay(DateUtil.currentDate(), -1);
            Date dateNow = DateUtil.currentDate();
            String startDate = DateUtil.formatDateNoHour(dateStart);
            String endDate = DateUtil.formatDateNoHour(dateNow);
            String hql = String.format("from %s where userId=?  and score>0 and ( addTime between date(?) and date(?))", entityClassName());
            List<ScoreHistory> scoreHistories = this.queryForList(hql, new Object[]{userId, startDate, endDate});
            return scoreHistories;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 获取用户的设备积分记录
     *
     * @param page
     * @param userId
     * @return
     */
    @Override
    public ResultModel queryHistoryByUserId(Page page, int userId) {
        String hql = String.format("from %s where userId=? ", entityClassName());
        List<ScoreHistory> scoreHistories = this.queryForListByPage(hql, new Object[]{userId}, page);
        String coungHql = String.format("select count(*) from %s where userId=? ", entityClassName());
        Long count = this.queryCount(coungHql, new Object[]{userId});
        ResultModel resultModel = new ResultModel(true, scoreHistories, count);
        return resultModel;
    }

    @Override
    public ResultModel queryDeviceScoreHistoryByParam(PageCondition pageCondition, int userId) {
        String sql = "select u.id as uid , u.username,u.phone,d.addtime as daddtime,d.deviceid,d.devicename,s.addtime,s.score,s.rankType " +
                " from tb_scorehistory s,tb_user u ,tb_device d  " +
                " where s.deviceid !=''  and s.taskid=0 and s.productid=0  and s.userid=u.id and d.userid =u.id and d.deviceid=s.deviceid ";
        StringBuilder sqlWhere = new StringBuilder();
        String[] column = {"uid", "username", "phone", "daddtime", "deviceid", "devicename", "addtime", "score", "ranktype"};
        ArrayList<Object> param = new ArrayList<Object>();

        if (userId != 0) {
            sqlWhere.append(" and u.id=?");
            param.add(userId);
        }

        if (pageCondition.isEmpty("username")) {
            String username = (String) pageCondition.getByKey("username");
            sqlWhere.append(" and u.username like ?");
            param.add("%" + username + "%");
        }
        if (pageCondition.isEmpty("rankType")) {
            int rankType = Integer.parseInt((String) pageCondition.getByKey("rankType"));
            sqlWhere.append(" and s.rankType=?");
            param.add(rankType);
        }
        if (pageCondition.isEmpty("phone")) {
            String phone = (String) pageCondition.getByKey("phone");
            sqlWhere.append(" and u.phone=?");
            param.add(phone);
        }
        if (pageCondition.isEmpty("deviceId")) {
            String deviceId = (String) pageCondition.getByKey("deviceId");
            sqlWhere.append(" and d.deviceId like ? ");
            param.add("%"+deviceId+"%");
        }
        if (pageCondition.isEmpty("userId")) {
            int uId = Integer.parseInt((String) pageCondition.getByKey("userId"));
            sqlWhere.append(" and u.id=?");
            param.add(uId);
        }
        if (pageCondition.isEmpty("flag")) {
            try {
                Date dateStart = DateUtil.addDay(DateUtil.currentDate(), -1);
                Date dateNow = DateUtil.currentDate();
                String startDate = DateUtil.formatDateNoHour(dateStart);
                String endDate = DateUtil.formatDateNoHour(dateNow);
                sqlWhere.append(" and s.addtime between date(?) and date(?)");
                param.add(startDate);
                param.add(endDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        sqlWhere.append(" order by s.addtime desc");
        List<Map<String, Object>> lists = this.queryForListObjectByPage(sql + sqlWhere + "", param.toArray(), pageCondition.getPage(), column);
        int count = this.queryCountByParam("select count(1) from tb_scorehistory s,tb_user u ,tb_device d " +
                " where s.deviceid !=''  and s.taskid=0 and s.productid=0  and s.userid=u.id and d.userid =u.id and d.deviceid=s.deviceid " + sqlWhere, param.toArray());
        ResultModel resultModel = new ResultModel(true, lists, count);
        return resultModel;
    }


    @Override
    public double querySumScoreYes() {
        try {
            ArrayList<Object> param = new ArrayList<Object>();
            String[] column = {"score"};
            Date dateStart = DateUtil.addDay(DateUtil.currentDate(), -1);
            Date dateNow = DateUtil.currentDate();
            String startDate = DateUtil.formatDateNoHour(dateStart);
            String endDate = DateUtil.formatDateNoHour(dateNow);
            param.add(startDate);
            param.add(endDate);
            Page page = new Page(1, 10);
            List<Map<String, Object>> lists = this.queryForListObjectByPage("select ifnull(sum(score),0),1 from tb_scorehistory where  addtime > date(?) and addtime < date(?) and score>0", param.toArray(), page, column);
            Object obj = lists.get(0).get("score");
            double score = Double.parseDouble(obj.toString());
            return score;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<Map<String, Object>> querySumScoreListYes() {
        try {
            ArrayList<Object> param = new ArrayList<Object>();
            String[] column = {"score", "userid", "stime"};
            Date dateStart = DateUtil.addDay(DateUtil.currentDate(), -1);
            Date dateNow = DateUtil.currentDate();
            String startDate = DateUtil.formatDateNoHour(dateStart);
            String endDate = DateUtil.formatDateNoHour(dateNow);
            param.add(startDate);
            param.add(startDate);
            param.add(endDate);
            Page page = new Page(1, 99999);
            List<Map<String, Object>> lists = this.queryForListObjectByPage("select ifnull(sum(score),0),userid,? from tb_scorehistory where  addtime > date(?) and addtime < date(?) and score>0 group by userid", param.toArray(), page, column);
            return lists;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void addOrUpdateShareScore(Device device, ScoreVo vo) {
        ScoreHistory yesScoreHistory = this.queryYestoryShareScoreByDevice(device);
        if (yesScoreHistory == null) {
            ScoreHistory scoreHistory = new ScoreHistory();
            scoreHistory.setUserId(device.getUserid());
            scoreHistory.setDeviceId(device.getDeviceId());
            scoreHistory.setRankType(0);
            scoreHistory.setScore(vo.getShareScore());
            scoreHistory.setDscore(vo.getDxScore());
            scoreHistory.setIscore(vo.getIntScore());
            scoreHistory.setTrantype(ConstantCode.TRANS_SHARE);
            scoreHistory.setHasAddUserScore(true);
            scoreHistory.setAddTime(DateUtil.getYestoryDayTimeStamp());
            this.add(scoreHistory);
        } else {
            double dScore = Utils.rounding(vo.getDxScore() - yesScoreHistory.getDscore());
            double iScore = Utils.rounding(vo.getIntScore() - yesScoreHistory.getIscore());

            yesScoreHistory.setUserId(device.getUserid());
            yesScoreHistory.setDeviceId(device.getDeviceId());
            yesScoreHistory.setRankType(0);
            yesScoreHistory.setScore(vo.getShareScore());
            yesScoreHistory.setDscore(vo.getDxScore());
            yesScoreHistory.setIscore(vo.getIntScore());
            yesScoreHistory.setTrantype(ConstantCode.TRANS_SHARE);
            yesScoreHistory.setHasAddUserScore(true);
            this.update(yesScoreHistory);

            vo.setIntScore((float) iScore);
            vo.setDxScore((float) dScore);
        }

        //添加int积分
        UserScore intScore = new UserScore();
        intScore.setRankType(RankType.RANK_INT);
        intScore.setUserId(device.getUserid());
        intScore.setScore(vo.getIntScore());
        userScoreDao.addOrUpdate(intScore);

        //添加电信积分
        UserScore oScore = new UserScore();
        oScore.setRankType(RankType.Rank_INIT);
        oScore.setUserId(device.getUserid());
        oScore.setScore(vo.getDxScore());
        userScoreDao.addOrUpdate(oScore);
    }

    @Override
    public void deleteShareScore(Device device) {
        ScoreHistory yesScoreHistory = this.queryYestoryShareScoreByDevice(device);
        if (yesScoreHistory != null) {
            double dScore = Utils.rounding(-yesScoreHistory.getDscore());
            double iScore = Utils.rounding(-yesScoreHistory.getIscore());

            this.delete(yesScoreHistory);
            //减少int积分
            UserScore intScore = new UserScore();
            intScore.setRankType(RankType.RANK_INT);
            intScore.setUserId(device.getUserid());
            intScore.setScore(iScore);
            userScoreDao.addOrUpdate(intScore);
            //减少电信积分
            UserScore oScore = new UserScore();
            oScore.setRankType(RankType.Rank_INIT);
            oScore.setUserId(device.getUserid());
            oScore.setScore(dScore);
            userScoreDao.addOrUpdate(oScore);
        }
    }


    private ScoreHistory queryYestoryShareScoreByDevice(Device device) {
        String hql = String.format("from %s where deviceid=? and addTime=? and trantype=?", entityClassName());
        Timestamp timestamp = DateUtil.getYestoryDayTimeStamp();
        ScoreHistory scoreHistory = this.queryForObject(hql, new Object[]{device.getDeviceId(), timestamp, ConstantCode.TRANS_SHARE});
        return scoreHistory;
    }


    @Override
    public long queryChangeIntToday(int userId) {


        String startDate = "";
        String endDate = "";
        try {
            Date dateStart = DateUtil.addDay(DateUtil.currentDate(), 1);
            Date dateNow = DateUtil.currentDate();
            endDate = DateUtil.formatDateNoHour(dateStart);
            startDate = DateUtil.formatDateNoHour(dateNow);
        } catch (Exception e) {
            System.out.println(e);
        }

        String countsql = String.format("select count(*) from %s where  intnum>0 and addtime between date(?) and date(?) and userId=? ", entityClassName());
        long count = this.queryCount(countsql, new Object[]{startDate, endDate, userId});
        return count;
    }
}
